<template>
  <div class="page-container">
    <!-- 左侧注册表单侧边栏 -->
    <div class="form-sidebar">
      <h2>设备注册</h2>
      <el-form ref="registerForm" :model="form" :rules="rules" label-width="100px">
        <!-- 设备基本信息 -->
        <el-form-item label="设备名称" prop="deviceName">
          <el-input v-model="form.deviceName" placeholder="请输入设备名称" />
        </el-form-item>
        <el-form-item label="设备编号" prop="deviceSn">
          <el-input v-model="form.deviceSn" placeholder="请输入唯一设备编号" />
        </el-form-item>
        <el-form-item label="设备类型" prop="deviceType">
          <el-select v-model="form.deviceType" placeholder="请选择设备类型">
            <el-option label="智能电表" value="electric" />
            <el-option label="智能水表" value="water" />
            <el-option label="智能气表" value="gas" />
          </el-select>
        </el-form-item>
        
        <!-- 地址搜索+地图关联 -->
        <el-form-item label="安装地址" prop="address">
          <el-input 
            v-model="form.address" 
            placeholder="输入地址（如：唐山市路北区XX路）" 
            id="addressInput"
          />
        </el-form-item>
        
        <!-- 经纬度（自动填充） -->
        <el-form-item label="经度" prop="longitude">
          <el-input v-model="form.longitude" placeholder="点击地图选择" readonly />
        </el-form-item>
        <el-form-item label="纬度" prop="latitude">
          <el-input v-model="form.latitude" placeholder="点击地图选择" readonly />
        </el-form-item>
        
        <!-- 提交/重置按钮 -->
        <el-form-item>
          <el-button type="primary" @click="handleSubmit">提交注册</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 右侧全屏地图 -->
    <div id="map-container"></div>
  </div>
</template>

<script>
import map from "@/api/manage/map";
import { addDevice } from "@/api/manage/device";

export default {
  data() {
    return {
      // 表单数据
      form: {
        deviceName: "",
        deviceSn: "",
        deviceType: "",
        address: "",
        longitude: "",
        latitude: ""
      },
      // 表单验证规则
      rules: {
        deviceName: [{ required: true, message: "请输入设备名称", trigger: "blur" }],
        deviceSn: [
          { required: true, message: "请输入设备编号", trigger: "blur" },
          { min: 5, max: 20, message: "编号长度5-20位", trigger: "blur" }
        ],
        deviceType: [{ required: true, message: "请选择设备类型", trigger: "change" }],
        address: [{ required: true, message: "请输入安装地址", trigger: "blur" }],
        longitude: [{ required: true, message: "请在地图选点", trigger: "blur" }],
        latitude: [{ required: true, message: "请在地图选点", trigger: "blur" }]
      },
      // 地图核心实例
      map: null,
      marker: null,
      geocoder: null,
      // 唐山开平区中心点
      center: { lng: 118.205, lat: 39.648 }
    };
  },
  mounted() {
    this.initMap();
    window.addEventListener("resize", () => this.map?.resize());
  },
  beforeDestroy() {
    // 简化地图清理逻辑
    if (this.map) {
      this.map.clearOverlays();
      this.map = null;
    }
    window.removeEventListener("resize", () => this.map?.resize());
  },
  methods: {
    // 初始化地图
    async initMap() {
      try {
        const BMap = await map.init();
        this.map = new BMap.Map("map-container");
        const centerPoint = new BMap.Point(this.center.lng, this.center.lat);
        
        // 地图基础配置
        this.map.centerAndZoom(centerPoint, 13);
        this.map.enableScrollWheelZoom(true);
        this.map.addControl(new BMap.NavigationControl());
        this.map.addControl(new BMap.ScaleControl());
        
        // 初始化地址解析器
        this.geocoder = new BMap.Geocoder();
        
        // 地图点击选点
        this.map.addEventListener("click", (e) => {
          this.marker && this.map.removeOverlay(this.marker);
          this.marker = new BMap.Marker(e.point);
          this.map.addOverlay(this.marker);
          this.form.longitude = e.point.lng.toFixed(6);
          this.form.latitude = e.point.lat.toFixed(6);
          // 点击地图反向补全地址
          this.geocoder.getLocation(e.point, (res) => res && (this.form.address = res.address));
        });
        
        // 地址自动完成
        const ac = new BMap.Autocomplete({ input: "addressInput", location: this.map });
        ac.addEventListener("onconfirm", (e) => {
          const addr = e.item.value;
          const fullAddr = `${addr.province}${addr.city}${addr.district}${addr.street}${addr.business}`;
          this.geocoder.getPoint(fullAddr, (point) => {
            if (point) {
              this.map.centerAndZoom(point, 15);
              this.marker && this.map.removeOverlay(this.marker);
              this.marker = new BMap.Marker(point);
              this.map.addOverlay(this.marker);
              this.form.longitude = point.lng.toFixed(6);
              this.form.latitude = point.lat.toFixed(6);
              this.form.address = fullAddr;
            } else {
              this.$message.warning("未找到该地址");
            }
          });
        });
      } catch (err) {
        console.error("地图加载失败:", err);
        document.getElementById("map-container").innerHTML = "地图加载失败，请刷新";
      }
    },

    // 提交表单
    handleSubmit() {
      this.$refs.registerForm.validate((valid) => {
        if (valid) {
          addDevice(this.form)
            .then(() => {
              this.$message.success("注册成功！");
              this.resetForm();
              this.marker && this.map.removeOverlay(this.marker);
              this.marker = null;
            })
            .catch((err) => this.$message.error("注册失败：" + (err.response?.data?.msg || "网络错误")));
        }
      });
    },

    // 重置表单
    resetForm() {
      this.$refs.registerForm.resetFields();
      this.form = { deviceName: "", deviceSn: "", deviceType: "", address: "", longitude: "", latitude: "" };
    }
  }
};
</script>

<style scoped>
.page-container {
  display: flex;
  width: 100vw;
  height: 100vh;
  overflow: hidden;
}

.form-sidebar {
  width: 380px;
  padding: 20px;
  background: #fff;
  box-shadow: 2px 0 5px rgba(0, 0, 0, 0.1);
  z-index: 10;
  overflow-y: auto;
}
api
.form-sidebar h2 {
  margin-bottom: 20px;
  color: #333;
  font-size: 18px;
  text-align: center;
}

#map-container {
  flex: 1;
  height: 100vh;
}

/* 响应式适配 */
@media (max-width: 768px) {
  .form-sidebar {
    width: 300px;
    padding: 15px;
  }
}
</style>